import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    
    // 实现获取电量信息的功能
    // 1、获取FlutterViewController
    let flutterController: FlutterViewController = window.rootViewController as! FlutterViewController
    
    // 2、创建 FlutterMethodChannel
    /**
       name：static const platform1 = const MethodChannel('com.jk/battery'); 的 com.jk/battery，名字自己定义： 域名/名字
       binaryMessenger:  二进制消息
     */
    let channel = FlutterMethodChannel(name: "com.jk/battery", binaryMessenger: flutterController.binaryMessenger);
    
    // 3.监听channnel方法
    channel.setMethodCallHandler { (call: FlutterMethodCall, result: @escaping FlutterResult) in
        guard call.method == "getBatteryInfo" else {
            // 找不到该方法
            result(FlutterMethodNotImplemented)
            return;
        }
        
        let device = UIDevice.current
        // 电池电量的探测，设置为true，才能更好的获取电量
        device.isBatteryMonitoringEnabled = true
        
        if device.batteryState == .unknown {
            result(FlutterError(code: "Unknown", message: "Battery is unknown", details: nil))
        } else {
            result(Int(device.batteryLevel * 100))
        }
        
    }
    
    
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}
